package com.xdja.study.mysql.dao;

import com.xdja.study.model.ErrorCodes;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.ResultSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;
@Component
public class UserConfigDaoVerticle extends AbstractVerticle {
    private static final Logger logger = LoggerFactory.getLogger(UserConfigDaoVerticle.class);

    private JDBCClient jdbcClient;

    public void start(Future<Void> startFuture) throws Exception {
        //创建数据库客户端
        jdbcClient = JDBCClient.createShared(vertx, config());
        jdbcClient.getConnection(ar -> {
            if (ar.failed()) {
                logger.error("Could not open a database connection", ar.cause());
                startFuture.fail(ar.cause());
            } else {
                vertx.eventBus().consumer("user.dao", message -> {
                    String userId = message.headers().get("userId");
                    getUserFromDB(userId, message);
                });  // 注册事件监听
                logger.debug("user.dao监听事件注册完成");
            }
        });
    }

    private void getUserFromDB(String userId, Message<Object> message) {
        String sql = "select c_id, c_password, c_name from t_update_user where c_id = " + userId;
        jdbcClient.query(sql, res -> {
            if (res.succeeded()) {
                ResultSet resultSet = res.result();
                List<JsonObject> rows = resultSet.getRows();
                message.reply(new JsonObject().put("rows", rows));
            } else {
                reportQueryError(message, res.cause());
            }
        });
    }

    private void reportQueryError(Message<Object> message, Throwable cause) {
        logger.error("Database query error", cause);
        message.fail(ErrorCodes.DB_ERROR.ordinal(), cause.getMessage());
    }
}
